

scroll('.win-category .first');
scroll('.win-category .second');
scroll('.win-category .third');



//提交按钮
var $resetDate = $('.win-category .btn-re'),
	$getDataBtn = $('.win-category .btn-conf');

//1.品类弹窗
var $addCategory = $('.user-center .company-activity .addbtn'),
	$win_category = $('.win-category');
	


//选中的品类    品类编辑时使用
var selectedCategory = {};
var categoryTree = null,
	searchTree = null;

$addCategory.on('click',function(){
	$win_category.fadeIn();
	overfhidden();
	
	//获取品类数据
	$.ajax({
		type:"get",
		url:"http://v4.www.laisj.com/publics/base/companyProductTagTree",
		async:true,
		success:function(res){
			console.log(res);
            changeList('.first .first-cate',res.tree,1);
            searchTree = res;
            return searchTree;
		},
		error:function(res){
			console.log(res);      //错误的对象
		}
	});
});
//2.关闭品类弹窗
$('.win-category .btn-close').click(function(){
	$resetDate.trigger('click');
})
//取消按钮
$resetDate.click(function(){
	$('.win-category .category input[type="reset"]').trigger('click');
	$('.win-category .check-wrap').removeClass('checked');
	$('.win-category .first-cate').html('');
	$('.win-category .second-cate').html('');
	$('.win-category .third').html('');
	$win_category.fadeOut();
});
//提交
$getDataBtn.click(function(){
	console.log(selectedCategory);
	var endArr = [],
		firstCate = $('.first-cate input:checked').val();
	var endData = selectedCategory[firstCate];	
	for(var i in endData){
		if(endData[i].length == 0){
			endArr.push(i);
		}
		if(endData[i].length>0){
			for(var j = 0;j<endData[i].length;j++){
				endArr.push(endData[i][j]);
			}
		}
	}
	console.log(endArr);
});




//1.1 修改添加dom                  index : 
function changeList(selector,data,index){
	var datahtml = '',
		id = null,
		$checked = null;
	
	//一二三级品类所有选项
	var $firstSelect = null,
		$secondSelect = null,
		$thirdSelect = null;
	
	var firstparent = null;
	
	//生成dom元素      index      1:一级品类  
	if(index==1){
		datahtml = listItem('first-cate',data,index);
		$(selector).html(datahtml);
		
		//标记已选择
		disabled($('.first-cate li'),data);
		
		//标记选中的二级品类
		$firstSelect  = $(selector+' input[name="first-cate"]');
		
		$firstSelect.change(function(){
			$checked = $(selector+' input[name="first-cate"]:checked');
			id =  $checked.data('val');
			
			//记录选中的一级品类
			firstparent = $checked.val();
			
			selectedCategory = {};
			selectedCategory[$checked.val()] = {};
			
			//改变一级品类时，清除二级、三级品类
			getchild(index);
			
			return changeList('.second .second-cate',data[parseInt(id)],2);
		});
	}
	if(index==2){
		datahtml = listItem('second-cate',data,index);
		$(selector).html(datahtml);
		
		//标记已选择
		disabled($(selector+'.second-cate li'),data.children);
		
		//标记选中的二级品类
		$secondSelect  = $(selector+' input[name="second-cate"]');
		
		//change   事件
		$secondSelect.change(function(){
			
			//判断是添加选中，还是取消选中
			var parent = $(this).data('parent');
			if($(this).is(':checked')){
				$(this).parent().addClass('checked');
				selectedCategory[parent][$(this).val()] = [];
			}else{
				$(this).parent().removeClass('checked');
				delete selectedCategory[parent][$(this).val()];

				if($.isEmptyObject(selectedCategory[parent])){
					changeBtn(false);
				}
			}
			
			//改变二级品类时，清除三级品类
			getchild(index);
			var $checked = $(selector+' input[name="second-cate"]:checked');
			for(var i = 0;i<$checked.length;i++){
				id =  $checked[i].dataset.val;
				//记录选中的二级品类
				changeList('.third',data.children[parseInt(id)],3);
			}
			
			calOther();
			
		});
		categoryTree = data.children;
	}
	if(index==3){
		selector = '.win-category '+selector;
		if(data.children.length>0){
			datahtml = '<div class="third-cate">'+
                          	'<p>'+data.name+'</p>'+
                            '<div class="checkbox-group clearfix">';
			
			datahtml = datahtml+listItem('third-cate',data,index)+ '</div>\n</div>';
			$(selector).append(datahtml);
			
			//标记已选择
			disabled($(selector+' .third-cate .check-wrap'),data.children);
			
			
			//标记选中的三级品类
			firstparent = $('.first-cate input:checked').val();
			
			$thirdSelect  = $(selector+' input[name="third-cate"]');
			$thirdSelect.unbind('change');
			
			//change事件
			$thirdSelect.bind('change',function(){
				if($(this).is(':checked')){
					$(this).parent().addClass('checked');
					selectedCategory[firstparent][$(this).data('parent')].push($(this).val());
				}else{
					$(this).parent().removeClass('checked');
					selectedCategory[firstparent][$(this).data('parent')].splice($.inArray($(this).val(),selectedCategory[firstparent][$(this).data('parent')]),1);  
				}
				
				//判断是否选择末级品类
				endCategory();

			});
			if(selectedCategory[firstparent][data.id].length>0){
				selectcate(selectedCategory[firstparent][data.id],$thirdSelect);	
			}
		}else{
			getchild(index);
		}
	}
	return selectedCategory,categoryTree;
}

//1.2 三级不同的品类
function listItem(selname,data,index){
	var datahtml = '',
		dataChild = null;
	//index   1:  一级品类   ,   2:  二级品类    ,  3:  三级品类
	if(index==1){
        for(var i=0;i<data.length;i++){
			datahtml = datahtml + '<li data-type="'+selname+'">\n' +
								'<div class="radio-wrap">\n' +
									'<span class="radio_btn">\n' +
					                    '<input type="radio" name="'+selname+'" id="'+selname+i+'" value="'+data[i].id+'" data-val="'+i+'" />\n' +
					                    '<span class="center"></span>\n' +
					                    '<span class="border"></span>\n' +
					                '</span>\n' +
					            	'<label class="check-text" for="'+selname+i+'">'+data[i].name+'</label>\n' +
					            '</div>\n' +
					        '</li>';
		}
        return  datahtml;
	}
	if(index==2){
		dataChild = data.children;
        for(var i=0;i<dataChild.length;i++){
			datahtml = datahtml + '<li data-type="'+selname+'">\n' +
								    '<div class="check-wrap">\n' +
					                    '<input type="checkbox" name="'+selname+'" id="'+selname+i+'" value="'+dataChild[i].id+'" data-parent="'+data.id+'"  data-val="'+i+'" />\n' +
						            	'<label class="check-text" for="'+selname+i+'"><span class="check"></span>'+dataChild[i].name+'</label>\n' +
						            '</div>\n' +
						       '</li>';
		} 
		return  datahtml;				       
	}
	if(index==3){
		dataChild = data.children;
       	for(var i=0;i<dataChild.length;i++){
			datahtml = datahtml + '<div class="check-wrap">\n' +
				                    '<input type="checkbox" name="'+selname+'" id="'+selname+dataChild[i].id+'" value="'+dataChild[i].id+'" data-parent="'+data.id+'"  data-val="'+i+'"  />\n' +
					            	'<label class="check-text" for="'+selname+dataChild[i].id+'"><span class="check"></span>'+dataChild[i].name+'</label>\n' +
					            '</div>\n';
		}
        return  datahtml;
	}
}



//1.3  change品类视图
function getchild(index){
    if(index==1){
        $('.win-category .second-cate').html('');
        $('.win-category .third').html('');
        changeBtn(false);
        return false;
    }
    if(index==2){
        $('.win-category .third').html('');
        return false;
    }
    if(index==3){
    	//末级品类
        console.log('no more');
        endCategory();
        return false;
    }
}



//1.4改变添加按钮   true:可点击    false:不可点击
function changeBtn(off){
    if(off){
        $getDataBtn.addClass('active');
        $getDataBtn.removeAttr('disabled');
        $getDataBtn.css('cursor','pointer');
    }else{
        $getDataBtn.removeClass('active');
        $getDataBtn.attr('disabled','true');
        $getDataBtn.css('cursor','not-allowed');
    }
}



//1.5编辑已选中的品类/已禁用的品类    二级、三级品类
function selectcate(selectedData,category){
	for(var i = 0;i<selectedData.length;i++){
		for(var j = 0;j<category.length;j++){
			if(selectedData[i]==category.eq(j).val()){
				//标记已选中
				category.eq(j).attr('checked','true');
				
				_this = category.eq(j);
				if(_this.is(':checked')){
					_this.parent().addClass('checked');
				}
				endCategory();
			}
		}
	}
}




//1.6 服务方判断是否选择末级品类
function endCategory(){
	var firstparent = $('.first-cate input:checked').val();
	var selected = selectedCategory[firstparent];
	var thirdLength = null,
		nowEndNum = 0;
	
	calOther();
	
    //判断是否选择末级品类
	for(var i in selected){
		for(var j in categoryTree){
			if(categoryTree[j].id == i){
				thirdLength = categoryTree[j].children.length;
				if(selected[i].length<1&&thirdLength>0){
					changeBtn(false);
					return false;
				}
			}
		}
	}
	changeBtn(true);
	
}
function calOther(){
	var firstparent = $('.first-cate input:checked').val();
	//判断还可以选择多少个品类    
	//1.1需求方：最多3个一级品类，二三级不限个数
    //1.2服务方：最多10个末级品类
    var off = true,
    	maxSize = 10,
    	selected = null,
    	nowEndNum = 0;
	var secondsel = $('.second-cate li'),
		thirdsel = $('.third-cate .check-wrap');
		
	//判断是否选择了二级品类	
    if($.isEmptyObject(selectedCategory[firstparent])){
    	off = false;
    	otherdisabled(off,secondsel,thirdsel);
    	return false;
    }
    
    //选择了二级品类	
    selected = selectedCategory[firstparent];
    for(var i in selected){
    	nowEndNum = nowEndNum + selected[i].length;
    }
    if(maxSize - searchTree.lastLevelSize - nowEndNum <=0){
    	otherdisabled(off,secondsel,thirdsel);
    }
    if(maxSize - searchTree.lastLevelSize - nowEndNum >0){
    	off = false;
    	otherdisabled(off,secondsel,thirdsel);
    }
}




//1.7设置选项不可用
function disabled(sel,noseleted){
	var _this = null,
		$input = sel.find('input');
	for(var i in noseleted){
		for(var j = 0;j<$input.length;j++){
			if(noseleted[i].id == $input.eq(j).val()&&noseleted[i].selected == 'true'){
				_this = sel.eq(j);
				_this.addClass('disabled');
				_this.find('input').attr('disabled','false');
				_this.find('label').css('cursor','not-allowed')
					.attr('disabled','false');
			}
		}
	}
}
//1.7.1 设置其他不可用(未选中)
//1.需求方：最多3个一级品类，二三级不限个数
//2.服务方：最多10个末级品类
function otherdisabled(off,secondsel,thirdsel){
	var $secondinput = secondsel.find('input'),
		$thirdinput = thirdsel.find('input');
	
	//禁用
	addDisable(secondsel,off);
	addDisable(thirdsel,off);
	if(!off){
		return false;
	}
	for(var i in selectedCategory){
//		//一级品类
//		for(var j = 0;j<$firstinput.length;j++){
//			if($firstinput.eq(j).val() == i){
//				_this = firstsel.eq(j);
//				addDisable(_this,false);
//			}
//		}
		for(var m in selectedCategory[i]){
			//二级品类
			for(var j = 0;j<$secondinput.length;j++){
				if($secondinput.eq(j).val() == m){
					_this = secondsel.eq(j);
					addDisable(_this,false);
				}
			}
			for(var n = 0;n<selectedCategory[i][m].length;n++){
				//三级品类
				for(var k = 0;k<$thirdinput.length;k++){
					console.log(selectedCategory[i][m][n],$thirdinput.eq(k).val());
					if($thirdinput.eq(k).val() == selectedCategory[i][m][n]){
						_this = thirdsel.eq(k);
						addDisable(_this,false);
					}
				}
			}
		}
	}
}
function addDisable(_this,off){
	//默认 true:禁用      false:启用
	_this.addClass('disabled');
	_this.find('input').attr('disabled','false');
	_this.find('label').css('cursor','not-allowed')
		.attr('disabled','false');
	if(!off){
		_this.removeClass('disabled');
		_this.find('input').removeAttr('disabled');
		_this.find('label').css('cursor','pointer')
			.removeAttr('disabled');
	}
}







//2. 模糊搜索
$('.win-category .searchinput').on('input propertychange',function(){
	searchKeywrod();
});
function searchKeywrod(){
	var _this = $('.win-category .searchinput');
	var cateTree = searchTree.tree,
		keyword = _this.val();
	
	var $select_list = $('.win-category .select_list');
	$select_list.html('');
	$select_list.slideDown();
	scroll('.win-category .select_list');
	$('.nicescroll-rails').css('z-index','999');
	
	for(var i in cateTree){
		if(cateTree[i].name.indexOf(keyword) != -1){
			for(var f in cateTree[i].children){
				
				if(cateTree[i].children[f].children.length>0){
					for(var t in cateTree[i].children[f].children){
						$select_list.append('<li class="li" data-firstid="'+cateTree[i].id+'" data-secondid="'+cateTree[i].children[f].id+'" data-thirdid="'+cateTree[i].children[f].children[t].id+'">'+cateTree[i].name+'-'+cateTree[i].children[f].name+'-'+cateTree[i].children[f].children[t].name+'</li>');
					}
				}
				if(cateTree[i].children[f].children.length<=0){
					$select_list.append('<li class="li" data-firstid="'+cateTree[i].id+'" data-secondid="'+cateTree[i].children[f].id+'">'+cateTree[i].id+'-'+cateTree[i].children[f].id+'</li>');
				}
			}
			
			searchResult();
			continue;
		}
		for(var j in cateTree[i].children){
			if(cateTree[i].children[j].name.indexOf(keyword) != -1){
//				console.log(cateTree[i].children[j].name);
				
				if(cateTree[i].children[j].children.length>0){
					for(var f in cateTree[i].children[j].children){
						$('<li class="li" data-firstid="'+cateTree[i].id+'" data-secondid="'+cateTree[i].children[j].id+'" data-thirdid="'+cateTree[i].children[j].children[f].id+'">'+cateTree[i].name+'-'+cateTree[i].children[j].name+'-'+cateTree[i].children[j].children[f].name+'</li>').insertBefore($select_list.find('.li').first());
					}
				}
				if(cateTree[i].children[j].children.length<=0){
					$('<li class="li" data-firstid="'+cateTree[i].id+'" data-secondid="'+cateTree[i].children[j].id+'">'+cateTree[i].name+'-'+cateTree[i].children[j].name+'</li>').insertBefore($select_list.find('.li').first());
				}
				
				searchResult();
				continue;
			}
			for(var m in cateTree[i].children[j].children){
				if(cateTree[i].children[j].children[m].name.indexOf(keyword) != -1){
//					console.log(cateTree[i].id,cateTree[i].children[j].id);
					
					$('<li class="li" data-firstid="'+cateTree[i].id+'" data-secondid="'+cateTree[i].children[j].id+'" data-thirdid="'+cateTree[i].children[j].children[m].id+'">'+cateTree[i].name+'-'+cateTree[i].children[j].name+'-'+cateTree[i].children[j].children[m].name+'</li>').insertBefore($select_list.find('.li').first());
					
					searchResult();
					continue;
				}
			}
		}
	}
}
function searchResult(){
	var $select_wrap = $('.win-category .searchinput'),
		$select_list = $('.win-category .select_list'),
		$select_li = $('.win-category .select_list .li'),
		firstid = null,
		secondid = null,
		thirdid = null;
		
	$select_li.unbind('click');	
	$select_li.click(function(){
		$select_list.slideUp();
		
		firstid = $(this).data('firstid'),
		secondid = $(this).data('secondid'),
		thirdid = $(this).data('thirdid');
		console.log(firstid,secondid,thirdid);
		
		//782 1423 1437
		for(var i = 0;i<$('.first-cate input').length;i++){
			if($('.first-cate input').eq(i).val() == firstid){
				console.log($('.first-cate input').eq(i).val(),firstid);
				$('.first-cate input').eq(i).trigger('click');
				
				for(var j = 0;j<$('.second-cate input').length;j++){
					if($('.second-cate input').eq(j).val() == secondid){
						console.log($('.second-cate input').eq(j).val(),secondid);
						if(!$('.second-cate input').eq(j).is(':checked')){
							$('.second-cate input').eq(j).parent().find('.check-text').trigger('click');
						}
						
						for(var n = 0;n<$('.third-cate input').length;n++){
							if($('.third-cate input').eq(n).val() == thirdid && !$('.third-cate input').eq(n).is(':checked')){
								console.log($('.third-cate input').eq(n).val(),thirdid);
								$('.third-cate input').eq(n).parent().find('.check-text').trigger('click');
							}
						}
					}
				}
			}					
		}
	});
	
	$select_wrap.unbind('click');
	$select_wrap.click(function(e){
		e.stopPropagation();
	});
	$('.win-category').click(function(){
		$select_list.slideUp();
	});
}




